angular.module('blog-app', [])
	.config(['$httpProvider', function($httpProvider) {
		$httpProvider.defaults.useXDomain = true;
		delete $httpProvider.defaults.headers.common['X-Requested-With'];
	}]);

var API_URL = 'https://7inpham.appspot.com/_ah/api/bapi/v1';
var cursor;

function BlogCtrl($scope, $http) {
	$scope.articles = [];
	$scope.isDone = false;
	$scope.hasMore = false;
	$scope.isLoading = true;
	$scope.isDetail = false;
	var id = window.location.search.substring(1).split('=')[1];
	if (id == null) {
		$http({
			method : 'GET',
			url : API_URL + '/blogpost'
		}).success(function(data, status, headers, config) {
			cursor = data.nextPageToken;
			angular.forEach(data.items, function(item) {
				$scope.articles.push(item);
				$scope.isLoading = false;
				$scope.isDone = true;
				$scope.hasMore = true;
			});
		}).error(function(data, status, headers, config) {
			console.log("error");
		});
	} else {
		$http({
			method : 'GET',
			url : API_URL + '/blogpost/' + id
		}).success(function(data, status, headers, config) {
			$scope.articles.push(data);
			$scope.isLoading = false;
			$scope.isDetail = true;
			$scope.isDone = true;
			
			var disqus_shortname = 'tinspham';
			var dsq = document.createElement('script');
			dsq.type = 'text/javascript';
			dsq.async = true;
			dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
			(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
		}).error(function(data, status, headers, config) {
			console.log("error");
		});
	}
	
	$scope.loadMore = function() {
		$scope.hasMore = false;
		$scope.isLoading = true;
		$http({
			method : 'GET',
			url : API_URL + '/blogpost?' + 'cursor=' + cursor
		}).success(function(data, status, headers, config) {
			cursor = data.nextPageToken;
			if (data.items != null) {
				angular.forEach(data.items, function(item) {
					$scope.articles.push(item);
					$scope.hasMore = true;
				});
			}
			$scope.isLoading = false;
		}).error(function(data, status, headers, config) {
			console.log("error");
		});
	};
}